package com.xuecheng.manage_media_proces.mq;

import com.alibaba.fastjson.JSONObject;
import com.xuecheng.framework.domain.media.MediaFile;
import com.xuecheng.framework.domain.media.MediaFileProcess_m3u8;
import com.xuecheng.framework.utils.M3U8VideoUtil;
import com.xuecheng.manage_media_proces.dao.MediaFileRepository;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * Rabbit接收视频处理消息
 */
@Component
public class MediaProcessTask {

    @Resource
    private MediaFileRepository mediaFileRepository;
    @Value("${xc-service-manage-media.mq.ffmpeg-path}")
    private String ffmpegPath;
    @Value("${xc-service-manage-media.mq.video-location}")
    private String mediaVideoPath;

    // 监听队列
    @RabbitListener(queues = "${xc-service-manage-media.mq.queue-media-video-processor}", containerFactory = "customContainerFactory")
    public void receiveMediaProcessTask(String msg) {
        try {
            Map<String, String> map = JSONObject.parseObject(msg, Map.class);
            String mediaId = map.get("mediaId");
            // 去数据库查mediaId;
            Optional<MediaFile> optional = mediaFileRepository.findById(mediaId);
            if (!optional.isPresent()) {
                return;
            }
            // 获取视频数据准备分片成m3u8
            MediaFile mediaFile = optional.get();
            M3U8VideoUtil.setFFmpegPath(ffmpegPath);
            mediaFile.setProcessStatus("303001");
            mediaFileRepository.save(mediaFile);
            List<File> list = M3U8VideoUtil.generateM3U8(mediaVideoPath + mediaFile.getFilePath(), mediaFile.getFileOriginalName(), mediaFile.getFileId());
            if (list == null || list.size() == 0) {
                // 没有返回m3u8
                mediaFile.setFileStatus("303003");
                return;
            } else {
                MediaFileProcess_m3u8 m3u8 = new MediaFileProcess_m3u8();
                List<String> s = new ArrayList<>();
                for (File file : list) {
                    s.add(file.getName());
                }
                m3u8.setTslist(s);
                mediaFile.setMediaFileProcess_m3u8(m3u8);
                mediaFile.setProcessStatus("303002");
                mediaFile.setFileUrl(mediaFile.getFilePath() + "/" + mediaFile.getFileId() + ".m3u8");
                mediaFileRepository.save(mediaFile);
            }
        } catch (Exception e) {
            System.out.println("收到未知消息:==>" + msg);
        }
    }
}
